import React, { useEffect, useState } from "react";
import { getLoginKey, getQr, checkStatus } from "@/api/user";
import { Image } from "antd";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setLoginStatus }from '@/store/modules/user'
export default function Login() {
  const [unikey, setUnikey] = useState(null);
  const [qrsrc, setQrSrc] = useState("");
  const navigate = useNavigate();
  const dispatch=useDispatch()
  const getQrFn = () => {
    getLoginKey().then((res) => {
      setUnikey(res.data.data.unikey);
      getQr({
        key: res.data.data.unikey,
        qrimg: import("@/assets/favicon.ico"),
      }).then((res) => {
        setQrSrc(res.data.data.qrimg);
      });
    });
  };

  useEffect(() => {
    getQrFn();
    const timer = setInterval(() => {
      checkStatus({ key: unikey }).then((res) => {
        switch (res.data.code) {
          case 803:
            console.log(res.data);
            localStorage.setItem("cookie", res.data.cookie);
            console.log("扫码成功!");
            document.cookie = `cookie=${res.data.cookie};expires=${new Date(
              new Date().getTime() + 24 * 60 * 60 * 1000
            ).toUTCString()}`;
            clearInterval(timer);
              dispatch(setLoginStatus(true))
            navigate("/");
            break;
          case 800:
            console.log("QR 码已过期");
            clearInterval(timer);
            break;
          case 801:
            console.log("等待扫码中...");
            break;
          case 802:
            console.log("扫码成功，等待确认中...");
            break;
          default:
            break;
        }
      });
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  });
  return (
    <div>
      <Image src={qrsrc}></Image>
    </div>
  );
}
